package middleware

import (
	"example.com/m/v2/model"
	"github.com/gin-gonic/gin"
	"github.com/gookit/color"
	"go.uber.org/zap"
	"net/http"
	"net/http/httputil"
	"runtime/debug"
)

// 异常信息从定义好的bizerr里面获取
func Fail(c *gin.Context, code int, message string) {
	c.JSON(code, model.ResultModel{
		Code:    code,
		Message: message,
		Data:    nil,
	})
	c.Abort()
}

func GlobalErrorMiddleware(logger *zap.Logger, stack bool) gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				color.HEX("#FFFF00").Println("panic..............")

				httpRequest, _ := httputil.DumpRequest(c.Request, false)

				//zap.L().Error(string(str)
				if stack {
					logger.Error("[Recovery from panic]",
						zap.Any("error", err),
						zap.String("request", string(httpRequest)),
						zap.String("stack", string(debug.Stack())),
					)
				} else {
					logger.Error("[Recovery from panic]",
						zap.Any("error", err),
						zap.String("zap.Any(\"error\", err),", string(httpRequest)),
					)
				}

				color.HEX("#FFFF00").Println("print log end..............")

				Fail(c, http.StatusInternalServerError, err.(string))
				c.Abort()
				return
			}
		}()
		c.Next()
	}
}
